package org.zjx.command;

import org.zjx.core.GameWindow;

import java.util.ArrayList;
import java.util.List;

/**
 * 复合指令基类（修复版本）
 */
public abstract class CompositeCommand extends Command {
    protected final List<Command> subCommands;

    public CompositeCommand(GameWindow window, String name) {
        super(window, false, name);
        this.subCommands = new ArrayList<>();
        // 在构造时初始化子命令，而不是在执行时
        initializeSubCommands();
    }

    /**
     * 抽象方法 - 子类实现具体的子命令初始化逻辑
     */
    protected abstract void initializeSubCommands();

    /**
     * 添加子指令
     */
    protected void addCommand(Command command) {
        if (command.getTargetWindow() != this.targetWindow) {
            throw new IllegalArgumentException("All sub-commands must target the same window");
        }
        subCommands.add(command);
    }

    @Override
    protected void doExecute() {
        System.out.println("[Composite] Starting composite command: " + getCommandName());
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < subCommands.size(); i++) {
            Command cmd = subCommands.get(i);
            System.out.println("[Composite] Executing sub-command " + (i+1) + "/" + subCommands.size() + ": " + cmd.getCommandName());
            cmd.execute();
        }

        long duration = System.currentTimeMillis() - startTime;
        System.out.println("[Composite] Completed composite command: " + getCommandName() + " in " + duration + "ms");
    }
}